package vn.aptech.leaveManagementSystem.view.director;

import java.awt.EventQueue;
import java.awt.ScrollPane;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JLayeredPane;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;

import vn.aptech.leaveManagementSystem.business.ViewReport;
import vn.aptech.leaveManagementSystem.business.dto.Application;
import vn.aptech.leaveManagementSystem.business.dto.Holiday;
import vn.aptech.leaveManagementSystem.business.dto.UserLoginInfo;
import vn.aptech.leaveManagementSystem.business.model.MyModel;
import vn.aptech.leaveManagementSystem.business.parse.MyParse;
import vn.aptech.leaveManagementSystem.dao.DBManager;
import vn.aptech.leaveManagementSystem.view.general.General;
import vn.aptech.leaveManagementSystem.view.util.ComboboxItem;
import vn.aptech.leaveManagementSystem.view.util.TimerTaskForDirector;

import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.UIManager;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.toedter.calendar.JCalendar;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JMonthChooser;
import com.toedter.calendar.JYearChooser;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JRadioButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class DirectorMainForm extends JFrame {
	private DefaultTableModel modelEmp;
	private JTable tbApproval;
	private JTable tbHoliday;
	private DefaultTableModel modelApproval;
	private DefaultTableModel modelHoliday;
	private MyModel mymodel;
	Timer timer;
	private JLayeredPane lpApproval;
	private JButton btnApprovalRefresh;
	private JYearChooser ycYear;
	private JDateChooser dchsrFromDate;
	private JDateChooser dchsrToDate;
	private JComboBox cbbDepartment;
	private JRadioButton rdbtnEmployeesInCompany;
	private JRadioButton rdbtnEmployeesInDepartment;
	private JRadioButton rdbtnReportByYear;
	private JRadioButton rdbtnReportByPeriod;
	private JPanel panel_1;
	private JLabel lblYear;
	private JLabel lblFromDate;
	private JLabel lblToDate;
	private JLabel lblDepartment;
	private JButton btnView;
	private JMenuItem miExit;
	private JMenuItem miChangePassword;
	private JMenuItem miLogOut;

	public DirectorMainForm() {
		InitGUI();
		InitAction();
		InitData();
	}

	private void InitData() {
		mymodel = new MyModel();
		UpdateSource();
	}

	private void InitAction() {
		// TODO Auto-generated method stub
		CreateTimer();
		tbApproval.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					if (tbApproval.getSelectedRow() != -1) {
						Vector<Object> v = (Vector<Object>) modelApproval
								.getDataVector().elementAt(
										tbApproval.getSelectedRow());
						ShowSubForm((Integer) v.get(0));
					}
				}
			}
		});

		btnApprovalRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				UpdateSource();
			}
		});

		rdbtnEmployeesInCompany.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				showAndHide();
			}
		});
		rdbtnEmployeesInDepartment.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				showAndHide();
			}
		});
		rdbtnReportByYear.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				showAndHide();
			}
		});
		rdbtnReportByPeriod.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				showAndHide();
			}
		});
		
		btnView.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (rdbtnEmployeesInCompany.isSelected())
				{
					if (rdbtnReportByYear.isSelected())
					{
						java.util.Date fromDate=new Date(ycYear.getYear()-1900, 0, 1);
						java.util.Date toDate=new Date(ycYear.getYear()-1900, 11, 31);
						ViewReport viewreport=new ViewReport();
						viewreport.viewReportTotalDaysLeaveInCompany(fromDate, toDate);	
					}
					else
					{
						java.util.Date fromDate=new Date(dchsrFromDate.getDate().getYear(),dchsrFromDate.getDate().getMonth(), dchsrFromDate.getDate().getDate());
						java.util.Date toDate=new Date(dchsrToDate.getDate().getYear(),dchsrToDate.getDate().getMonth(), dchsrToDate.getDate().getDate());
						ViewReport viewreport=new ViewReport();
						viewreport.viewReportTotalDaysLeaveInCompany(fromDate, toDate);	
					}
				}
				else
				{
					if (rdbtnReportByYear.isSelected())
					{
						java.util.Date fromDate=new Date(ycYear.getYear()-1900, 0, 1);
						java.util.Date toDate=new Date(ycYear.getYear()-1900, 11, 31);
						ComboboxItem item=(ComboboxItem) cbbDepartment.getSelectedItem();
						int idDep=(Integer) item.getValue();
						ViewReport viewreport=new ViewReport();
						viewreport.viewReportTotalDaysLeaveInDepartment(idDep, fromDate, toDate);
					}
					else
					{
						java.util.Date fromDate=new Date(dchsrFromDate.getDate().getYear(),dchsrFromDate.getDate().getMonth(), dchsrFromDate.getDate().getDate());
						java.util.Date toDate=new Date(dchsrToDate.getDate().getYear(),dchsrToDate.getDate().getMonth(), dchsrToDate.getDate().getDate());
						System.out.println(fromDate.toString());
						ComboboxItem item=(ComboboxItem) cbbDepartment.getSelectedItem();
						int idDep=(Integer) item.getValue();
						ViewReport viewreport=new ViewReport();
						viewreport.viewReportTotalDaysLeaveInDepartment(idDep, fromDate, toDate);	
					}
				}
			}
		});
		
		miExit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				General gen=new General();
				gen.exit();
			}
		});
		
		miChangePassword.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				General gen=new General();
				gen.changPassword(UserLoginInfo.getUserInfo().getIDEmp());
			}
		});
		
		miLogOut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				General gen=new General();
				gen.logout();
				close();
			}
		});
	}

	public void showAndHide()
	{
		if (rdbtnEmployeesInCompany.isSelected())
		{
			cbbDepartment.setVisible(false);
			lblDepartment.setVisible(false);
			if (rdbtnReportByYear.isSelected())
			{
				ycYear.setVisible(true);
				dchsrFromDate.setVisible(false);
				dchsrToDate.setVisible(false);
				
				lblYear.setVisible(true);
				lblFromDate.setVisible(false);
				lblToDate.setVisible(false);
			}
			else
			{
				dchsrFromDate.setVisible(true);
				dchsrToDate.setVisible(true);
				ycYear.setVisible(false);
				
				lblYear.setVisible(false);
				lblFromDate.setVisible(true);
				lblToDate.setVisible(true);
			}
		}
		else
		{
			cbbDepartment.setVisible(true);
			lblDepartment.setVisible(true);
			if (rdbtnReportByYear.isSelected())
			{
				ycYear.setVisible(true);
				dchsrFromDate.setVisible(false);
				dchsrToDate.setVisible(false);
				
				lblYear.setVisible(true);
				lblFromDate.setVisible(false);
				lblToDate.setVisible(false);
			}
			else
			{
				dchsrFromDate.setVisible(true);
				dchsrToDate.setVisible(true);
				ycYear.setVisible(false);
				
				lblYear.setVisible(false);
				lblFromDate.setVisible(true);
				lblToDate.setVisible(true);
			}
		}
	}
	
	public void ShowSubForm(int idApp) {
		ApprovalApplicationFormForDirector approvalForm = new ApprovalApplicationFormForDirector(
				this, idApp);
		approvalForm.setVisible(true);
		approvalForm.setAlwaysOnTop(true);
		this.setEnabled(false);
	}

	private void InitGUI() {
		setTitle("Director Main Form");
		setBounds(100, 100, 913, 565);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		getContentPane().setLayout(null);
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBorderPainted(false);
		menuBar.setBounds(0, 0, 634, 21);
		getContentPane().add(menuBar);
		JMenu mnGeneral = new JMenu("General");
		menuBar.add(mnGeneral);
		
		miChangePassword = new JMenuItem("Change Password");
		miChangePassword.setIcon(new ImageIcon("icons/gif/16x16/Modify.gif"));
		mnGeneral.add(miChangePassword);
		
		miLogOut = new JMenuItem("Logout");
		miLogOut.setIcon(new ImageIcon("icons/png/16x16/Logout.png"));
		mnGeneral.add(miLogOut);
		
		miExit = new JMenuItem("Exit");
		miExit.setIcon(new ImageIcon("icons/gif/16x16/Exit.gif"));
		mnGeneral.add(miExit);
		
		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		
		JTabbedPane tpMain = new JTabbedPane(JTabbedPane.TOP);
		tpMain.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
		tpMain.setBounds(81, 22, 813, 514);
		getContentPane().add(tpMain);
		modelEmp=new DefaultTableModel(
				new Object[][]{},
				new String[] {
						"ID","FirstName", "LastName", "Gender", "Department","Position","Birthday", "Address", "Email", "Phone", "Join Date", "UserName", "Status"
				});
		
		lpApproval = new JLayeredPane();
		tpMain.addTab("Approval", null, lpApproval, null);
		
		JPanel pnlApproval = new JPanel();
		pnlApproval.setBounds(10, 11, 792, 458);
		lpApproval.add(pnlApproval);
		pnlApproval.setLayout(null);
		
		tbApproval = new JTable();
		modelApproval=new DefaultTableModel()
		{
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		modelApproval.addColumn("ID App.");
		modelApproval.addColumn("First Name");
		modelApproval.addColumn("Last Name");
		modelApproval.addColumn("Department");
		modelApproval.addColumn("Position");
		modelApproval.addColumn("Status");
		tbApproval.setModel(modelApproval);
		tbApproval.getColumnModel().getColumn(0).setPreferredWidth(20);
		tbApproval.getColumnModel().getColumn(1).setPreferredWidth(50);
		tbApproval.getColumnModel().getColumn(2).setPreferredWidth(50);
		tbApproval.getColumnModel().getColumn(3).setPreferredWidth(65);
		tbApproval.getColumnModel().getColumn(4).setPreferredWidth(65);
		tbApproval.getColumnModel().getColumn(5).setPreferredWidth(140);
		tbApproval.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane spApproval=new JScrollPane(tbApproval);
		spApproval.setBounds(10, 34, 782, 315);
		
		pnlApproval.add(spApproval);
		
		JLabel lblHoliday = new JLabel("Upcoming holiday");
		lblHoliday.setForeground(Color.BLUE);
		lblHoliday.setFont(new Font("Tahoma", Font.PLAIN, 11));
		lblHoliday.setBounds(10, 360, 98, 14);
		pnlApproval.add(lblHoliday);
		//------------------------------------------------------------
		//Table Holiday
		tbHoliday=new JTable();
		modelHoliday=new DefaultTableModel()
		{
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		modelHoliday.addColumn("ID");
		modelHoliday.addColumn("Event");
		modelHoliday.addColumn("Start Date");
		modelHoliday.addColumn("End Date");
		tbHoliday.setModel(modelHoliday);
		tbHoliday.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane spHoliday = new JScrollPane(tbHoliday);
		spHoliday.setBounds(10, 376, 782, 63);
		pnlApproval.add(spHoliday);
		
		JToolBar tbrApproval = new JToolBar();
		tbrApproval.setBounds(10, 0, 782, 23);
		pnlApproval.add(tbrApproval);
		
		btnApprovalRefresh = new JButton("Refresh");
		btnApprovalRefresh.setIcon(new ImageIcon("icons/gif/16x16/Refresh.gif"));
		tbrApproval.add(btnApprovalRefresh);
		
		JLayeredPane lpViewReport = new JLayeredPane();
		tpMain.addTab("View Report", null, lpViewReport, null);
		ButtonGroup bg1=new ButtonGroup();
		//////////////////
		
		lpViewReport.setLayout(null);
		ButtonGroup bg2=new ButtonGroup();
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "REPORT TOTAL DAYS LEAVE", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBounds(153, 74, 466, 325);
		lpViewReport.add(panel);
		panel.setLayout(null);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(33, 31, 402, 47);
		panel.add(panel_2);
		panel_2.setBorder(new TitledBorder(null, "Report of", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		panel_2.setLayout(null);
		
		/////////////////
		rdbtnEmployeesInCompany = new JRadioButton("All Employees in Company");
		rdbtnEmployeesInCompany.setBounds(23, 19, 193, 23);
		rdbtnEmployeesInCompany.setSelected(true);
		panel_2.add(rdbtnEmployeesInCompany);
		
		rdbtnEmployeesInDepartment = new JRadioButton("Employees in Department");
		rdbtnEmployeesInDepartment.setBounds(218, 19, 178, 23);
		panel_2.add(rdbtnEmployeesInDepartment);
		bg1.add(rdbtnEmployeesInCompany);
		bg1.add(rdbtnEmployeesInDepartment);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBounds(33, 80, 402, 47);
		panel.add(panel_3);
		panel_3.setBorder(new TitledBorder(null, "Report by", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_3.setLayout(null);
		
		
		rdbtnReportByYear = new JRadioButton("Year");
		rdbtnReportByYear.setBounds(22, 20, 109, 23);
		rdbtnReportByYear.setSelected(true);
		panel_3.add(rdbtnReportByYear);
		
		rdbtnReportByPeriod = new JRadioButton("Period of time");
		rdbtnReportByPeriod.setBounds(219, 20, 109, 23);
		panel_3.add(rdbtnReportByPeriod);
		bg2.add(rdbtnReportByYear);
		bg2.add(rdbtnReportByPeriod);
		
		btnView = new JButton("View Report");
		btnView.setIcon(new ImageIcon("icons/gif/16x16/Report.gif"));
		btnView.setBounds(157, 284, 156, 23);
		panel.add(btnView);
		
		panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Enter the necessary information", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(33, 138, 402, 134);
		panel.add(panel_1);
		
		ycYear = new JYearChooser();
		ycYear.setBounds(89, 28, 283, 20);
		
		dchsrFromDate = new JDateChooser();
		dchsrFromDate.setBounds(89, 53, 283, 20);
		
		dchsrToDate = new JDateChooser();
		dchsrToDate.setBounds(89, 78, 283, 20);
		
		////////////////////////////////////////////////////
		cbbDepartment = new JComboBox();
		cbbDepartment.setBounds(89, 103, 283, 20);
		mymodel=new MyModel();
		try {
			ResultSet rs=mymodel.departments.getDepartmentList();
			while (rs.next())
			{
				ComboboxItem item=new ComboboxItem(rs.getObject("IDDepartment"), rs.getObject("DepartmentName"));
				cbbDepartment.addItem(item);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		///////////////////////////////////////////////////
		panel_1.setLayout(null);
		panel_1.add(ycYear);
		panel_1.add(dchsrFromDate);
		panel_1.add(dchsrToDate);
		panel_1.add(cbbDepartment);
		lblYear = new JLabel("Year:");
		lblYear.setBounds(10, 28, 77, 20);
		panel_1.add(lblYear);
		lblYear.setPreferredSize(new Dimension(100, 20));
		
		lblFromDate = new JLabel("From Date:");
		panel_1.add(lblFromDate);
		lblFromDate.setPreferredSize(new Dimension(100, 20));
		lblFromDate.setBounds(new Rectangle(10, 53, 77, 20));
		
		lblToDate = new JLabel("To Date:");
		panel_1.add(lblToDate);
		lblToDate.setPreferredSize(new Dimension(100, 20));
		lblToDate.setBounds(new Rectangle(10, 78, 77, 20));
		
		lblDepartment = new JLabel("Department:");
		panel_1.add(lblDepartment);
		lblDepartment.setPreferredSize(new Dimension(100, 20));
		lblDepartment.setBounds(new Rectangle(10, 103, 77, 20));
		//------------------------------------------------------------
		
		
		JLabel jlblBackground = new JLabel("");
		jlblBackground.setBounds(0, 23, 82, 512);
		getContentPane().add(jlblBackground);
		jlblBackground.setBorder(new LineBorder(new Color(0, 0, 0)));
		jlblBackground.setIcon(new ImageIcon("backgrounds/Background0.png"));
		
		JLabel lblWellcome = new JLabel("New label");
		lblWellcome.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
		lblWellcome.setHorizontalAlignment(SwingConstants.RIGHT);
		lblWellcome.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblWellcome.setForeground(UIManager.getColor("ComboBox.selectionBackground"));
		lblWellcome.setBounds(637, 0, 257, 21);
		
		getContentPane().add(lblWellcome);
		String strWellcome="User: ";
		if (UserLoginInfo.getUserInfo().isGender())
			strWellcome=strWellcome+"Mr. ";
		else
			strWellcome=strWellcome+"Mrs. ";
		strWellcome=strWellcome+UserLoginInfo.getUserInfo().getFirstName()+" "+UserLoginInfo.getUserInfo().getLastName();
		lblWellcome.setText(strWellcome);
		showAndHide();
	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}

	public void RemoveAllRows(DefaultTableModel tablemodel) {
		int n = tablemodel.getRowCount();
		for (int i = n - 1; i >= 0; i--) {
			tablemodel.removeRow(i);
		}
	}

	public void UpdateDataTableApproval() {
		ResultSet rs;
		try {
			rs = mymodel.applications.getApplicationsNotApproveForDirector();
			RemoveAllRows(modelApproval);
			while (rs.next()) {
				Vector<Object> v = new Vector<Object>();
				v.add(rs.getObject("IDApplication"));
				v.add(rs.getObject("FirstName"));
				v.add(rs.getObject("LastName"));
				v.add(rs.getObject("DepartmentName"));
				v.add(rs.getObject("PositionName"));
				int stt = rs.getInt("Status");
				String desStt = null;
				switch (stt) {
				case 0:
					desStt = "Awaiting approval to Leave";
					break;
				case 4:
					desStt = "Awaiting approval to Cancel Leaving";
					break;
				default:
					break;
				}
				v.add(desStt);
				modelApproval.insertRow(tbApproval.getRowCount(), v);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void UpdateDataTableHoliday() {
		try {
			ResultSet rs = mymodel.holidays.getUpcomingHolidays();
			RemoveAllRows(modelHoliday);
			while (rs.next()) {
				Holiday tempHol = MyParse.toHoliday(rs);
				Vector<Object> v = new Vector<Object>();
				v.add(tempHol.getIDHoliday());
				v.add(tempHol.getEvent());
				v.add(tempHol.getStartDate().toString());
				v.add(tempHol.getEndDate().toString());
				modelHoliday.insertRow(tbHoliday.getRowCount(), v);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void UpdateSource() {
		UpdateDataTableApproval();
		UpdateDataTableHoliday();
	}

	public void close()
	{
		dispose();
	}
	
	public void CreateTimer() {
		timer = new Timer();
		timer.schedule(new TimerTaskForDirector(this), 1000, 24000);
	}
}
